<?php

require "library/okch.inc";


class BaseModule extends Module
{
	public $helper;
	
	public function __config()
	{
		
		$this->helper = new OKHelper($this->site);
	}
	
	public function __default()
	{
		$this->LoginAction();
	}
	
	public function LoginAction()
	{
		session_start();
		
		if ( isset( $_SESSION['time'] ) )
		{
			// Have session
			$this->db->driver_connect();
			
			if ( isset( $_SESSION['uid'] ) )
			{
				// Authorised
				$uid = intval($_SESSION['uid']);
				$this->db->select("*", "admins")->where("`id`='$uid'")->result();
				if ( $this->db->fetch_bool() )
				{
					// Have account
					header("Location: /admin/panel");
					return;
				}
			}
		}
		else
		{
			// New session
			// Only show login form
			session_destroy();
		}
		
		// ------------------------------------------
		// Show login form
		header("Content-type: text/html; charset=utf-8");
		$this->page->template = "login/index.tpl";
		$this->page->add_css("base.css");
		$this->page->add_css("login.css");
		$this->page->add_js("jquery-2.0.0.js");
		$this->page->add_js("base.js");
		$this->page->loadTplToVar("body", "login/loginform.tpl");
		$this->page->title("_LoginTitle", true);
		
		unset( $_SESSION['login_error'] );
	}
	
	public function LogininAction()
	{
		session_start();
		session_unset();
		$this->db->driver_connect();
		
		$email = $this->site->_post("loginEmail");
		$passw = md5($this->site->_post("loginPass"));
		
		if ( !$email || !$passw )
		{
			header("Location: /admin/");
			return;
		}
		
		$this->db->select("*", "admins")->where("`email`='$email' AND `passw`='$passw'")->result();
		$a = $this->db->fetch_array();
		if ( $a != false )
		{
			$_SESSION['uid'] = intval($a['id']);
			$_SESSION['time'] = time();
			header("Location: /admin/panel/");
			return;
		}
		else
		{
			$_SESSION['time'] = time();
			$_SESSION['login_error'] = 1;
			header("Location: /admin/");
			return;
		}
		
	}
	
	
	public function RecoverAction()
	{
		header("Location: /admin/");
		return;
	}
	
	
	public function LogoutAction()
	{
		session_start();
		session_destroy();
		header("Location: /admin/");
	}
}
